function fetch_students_info() {
    fetch('/show_students',{
        method: 'GET',
        headers: {
            'X-Internal-Request': 'True'
        }
    })
    .then(response => response.json())
    .then(data => {
        const tbody = document.querySelector('#student_info tbody')
        data.forEach(element => {
            const row = document.createElement('tr')
            Object.values(element).forEach(value => {
                const cell = document.createElement('td')
                cell.textContent = value
                row.appendChild(cell)
            })
            tbody.appendChild(row)
        });
    })
    .catch(error => console.error('Error:', error));
}

function fetch_course_info() {
    fetch('/show_course',{
        method: 'GET',
        headers: {
            'X-Internal-Request': 'True'
        }
    })
    .then(response => response.json())
    .then(data => {
        const tbody = document.querySelector('#course_info tbody')
        data.forEach(element => {
            const row = document.createElement('tr')
            Object.values(element).forEach(value => {
                const cell = document.createElement('td')
                cell.textContent = value
                row.appendChild(cell)
            })
            tbody.appendChild(row)
        });
    })
    .catch(error => console.error('Error:', error));
}

function fetch_grades_info(name= null) {
    fetch('/show_grades',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Internal-Request': 'True'
        },
        body: JSON.stringify({name:name})
    })
    .then(response => response.json())
    .then(data => {
        const tbody = document.querySelector('#score_table tbody')
        data.forEach(element => {
            const row = document.createElement('tr')
            Object.values(element).forEach(value => {
                const cell = document.createElement('td')
                cell.textContent = value
                row.appendChild(cell)
            })
            tbody.appendChild(row)
        });
    })
    .catch(error => console.error('Error:', error));
}

function commit_score() {
    const score_form = document.getElementById('add_score_form')
    const score_table = document.getElementById('score_table').getElementsByTagName('tbody')[0]

    score_form.addEventListener('submit', function(event){
        event.preventDefault()
        const name = document.getElementById('name').value
        const course = document.getElementById('course_for_score').value
        const score = document.getElementById('score').value

        const row = score_table.insertRow()
        const cell1 = row.insertCell(0)
        const cell2 = row.insertCell(1)
        const cell3 = row.insertCell(2)
        cell1.textContent = name
        cell2.textContent = course
        cell3.textContent = score

        score_form.reset()
    })

    document.getElementById('commit_score').addEventListener('click',function(event){
        event.preventDefault()
        var table = document.getElementById('score_table')
        var rows = table.getElementsByTagName('tr')
        var info = []
        for (var i = 1;i<rows.length;){
            var name = rows[i].cells[0].innerText
            var course = rows[i].cells[1].innerText
            var grade = rows[i].cells[2].innerText
            info.push({'name':name,'course':course,'grade':grade})
            table.deleteRow(i)
        }
        var xhr = new XMLHttpRequest()
        xhr.open("POST","/get_score_info",true)
        xhr.setRequestHeader("X-Internal-Request", "True")
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200){
                var response = JSON.parse(xhr.responseText)
                document.getElementById('score_container').style.display = 'block'
                if (response.status === "error") {
                    document.getElementById('score_iframe').contentDocument.body.innerHTML = response.message
                } else if (response.status === 'success') {
                    document.getElementById('score_iframe').contentDocument.body.innerHTML = response.message
                }
                setTimeout(function() {
                    document.getElementById('score_container').style.display = 'none';
                }, 3000)
            }
        }
        xhr.send(JSON.stringify({'info':info}))
    })
}

function commit_course() {
    const course_form = document.getElementById('add_course_form')
    const course_table = document.getElementById('course_table').getElementsByTagName('tbody')[0]

    course_form.addEventListener('submit', function(event){
        event.preventDefault()
        const course = document.getElementById('course_for_add').value

        const row = course_table.insertRow()
        const cell = row.insertCell(0)
        cell.textContent = course

        course_form.reset()
    })

    document.getElementById('commit_course').addEventListener('click', function(event) {
        event.preventDefault()
        var table = document.getElementById('course_table')
        var rows = table.getElementsByTagName('tr')
        var courses = []
        for (var i = 1; i < rows.length;) {
            var course = rows[i].cells[0].innerText
            courses.push(course)
            table.deleteRow(i)
        }
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/get_course_info", true)
        xhr.setRequestHeader("X-Internal-Request", "True")
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.responseText)
                document.getElementById('course_container').style.display = 'block'
                if (response.status === "error") {
                    document.getElementById('course_iframe').contentDocument.body.innerHTML = response.message
                } else if (response.status === 'success') {
                    document.getElementById('course_iframe').contentDocument.body.innerHTML = response.message
                }
                setTimeout(function() {
                    document.getElementById('course_container').style.display = 'none';
                }, 3000)
            }
        }
        xhr.send(JSON.stringify({ courses: courses }))
    })
}

document.addEventListener('DOMContentLoaded', function () {
    var userType = document.getElementById('user_info').textContent.match(/\((.*?)\)/)[1]
    var userName = document.getElementById('user_info').textContent.match(/.*?: (.*?) \(/)[1]
    const student_info = document.getElementById('student_info')
    const course_info = document.getElementById('course_info')
    const option = document.getElementById('options')
    const add_score_option = document.getElementById('add_score_option')
    const add_course_option = document.getElementById('add_course_option')
    const add_score_section = document.getElementById('add_score_section')
    const add_course_section = document.getElementById('add_course_section')
    const score_table_section = document.getElementById('score_table').closest('section')
    const course_table_section = document.getElementById('course_table').closest('section')

    
    if (userType === 'student') {
        // 隐藏添加学生表单区域
        option.style.display = 'none'
        student_info.style.display = 'none'
        course_info.style.display = 'none'
        add_score_section.style.display = 'none'
        score_table_section.style.display = 'block'
        add_course_section.style.display = 'none'
        course_table_section.style.display = 'none'
        document.getElementById('commit_score').style.display = 'none'
        fetch_grades_info(userName)
    } else if (userType === 'teacher') {
        // 显示添加学生表单区域
        student_info.style.display = 'block'
        course_info.style.display = 'block'
        add_score_section.style.display = 'block'
        score_table_section.style.display = 'block'
        add_course_section.style.display = 'none'
        course_table_section.style.display = 'none'
        fetch_students_info()
        fetch_course_info()
    }

    add_score_option.addEventListener('click', function () {
        fetch_course_info()
        student_info.style.display = 'block'
        course_info.style.display = 'block'
        add_course_section.style.display = 'none';
        course_table_section.style.display = 'none';
        add_score_section.style.display = 'block';
        score_table_section.style.display = 'block';
    });

    add_course_option.addEventListener('click', function () {
        student_info.style.display = 'none'
        course_info.style.display = 'none'
        add_score_section.style.display = 'none';
        score_table_section.style.display = 'none';
        add_course_section.style.display = 'block';
        course_table_section.style.display = 'block';
    });

    commit_score()
    commit_course()
});